import {TableListData} from '@/data';
import {AnyAction, Reducer} from 'redux';
import {EffectsCommandMap} from 'dva';
import {add, edit, query, remove} from "./service";
import {message} from 'antd';

export interface IStateType {
  data: TableListData;
}

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: IStateType) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: IStateType;
  effects: {
    fetch: Effect;
    add: Effect;
    edit: Effect;
    remove: Effect;
  };
  reducers: {
    save: Reducer<IStateType>;
  };
}

const Model: ModelType = {
  namespace: 'BLOCK_NAME_CAMEL_CASE',

  state: {
    data: {
      list: [],
      pagination: {},
    },
  },

  effects: {
    * fetch({pagination, filters}, {call, put}) {
      try {
        const response = yield call(query, filters, pagination);
        yield put({type: 'save', payload: response});
      } catch (err) {
        console.error(err);
      }
    },
    * add({payload: {data, callback}}, {call, put}) {
      try {
        yield call(add, data);
        if (callback) callback();
        message.success('添加员工成功！');
        yield put({type: 'fetch'});
      } catch (err) {
        message.error(`添加员工失败:${err}`);
      }
    },
    *edit({ payload: { data, callback } }, { call, put }) {
      try {
        yield call(edit, data);
        if (callback) callback();
        message.success('修改员工成功！');
        yield put({ type: 'fetch' });
      } catch (err) {
        message.error(`修改员工失败:${err}`);
      }
    },
    *remove({ data }, { call, put }) {
      try {
        yield call(remove, data);
        message.success('删除员工成功！');
        yield put({ type: 'fetch' });
      } catch (err) {
        message.error(`删除员工失败:${err}`);
      }
    },
  },

  reducers: {
    save(state, {payload}) {
      const data = {
        list: payload.data,
        pagination: {total: payload.total, pageSize: payload.size, current: payload.page},
      };
      return {...state, data};
    },
  }
};
export default Model;
